const cloud = require('wx-server-sdk')
const axios = require('axios')
cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV })

const db = cloud.database()

/**
 * 更新学校经纬度任务
 * @param {Object} event 
 * @returns 
 */
async function updateSchoolLocationTask(event) {
  try {
    console.log("updateSchoolLocationTask start");
    
    // 获取学校列表配置
    const schoolRes = await db.collection('config').where({ config_name: 'school_list' }).get();
    const schoolList = schoolRes.data[0]?.content || [];
    
    // 更新每个学校的经纬度
    for (let school of schoolList) {
      const location = await getSchoolLocation(school.address_name,school.city);
      if (location) {
        school.longitude = location.longitude;
        school.latitude = location.latitude;
        console.log(`更新学校位置成功: ${school.address_name}`, location);
      } else {
        console.log(`未找到学校位置: ${school.address_name}`);
      }
    }
    
    // 更新数据库
    await db.collection('config').where({ config_name: 'school_list' }).update({
      data: {
        content: schoolList
      }
    });

    return {
      success: true,
      message: '学校位置更新任务执行成功'
    }
  } catch (error) {
    console.error('更新学校位置任务失败:', error)
    console.error(error.stack);
    return {
      success: false,
      message: error.message || '更新学校位置任务失败'
    }
  }
}

/**
 * 使用高德地图API获取学校位置
 * @param {string} schoolName 学校名称
 * @returns {Promise<{longitude: string, latitude: string} | null>}
 */
async function getSchoolLocation(schoolName, city) {
  try {
    // 高德地图API密钥，需要替换成你的密钥
    const key = '218adf96de987070eb25af864056c6e3';
    const url = `https://restapi.amap.com/v3/place/text?key=${key}&keywords=${encodeURIComponent(schoolName)}&city=${encodeURIComponent(city)}&types=141201&output=json`;
    
    const response = await axios.get(url);
    const pois = response.data.pois;
    
    if (pois && pois.length > 0) {
      const location = pois[0].location.split(',');
      return {
        longitude: location[0],
        latitude: location[1]
      };
    }
    return null;
  } catch (error) {
    console.error('获取学校位置失败:', error);
    return null;
  }
}

module.exports = updateSchoolLocationTask 